package admin_user_api

import (
	"blog_go/global"
	"blog_go/models"
	"blog_go/models/ctype"
	"blog_go/models/res"
	"blog_go/utils"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
)

type UserAddReq struct {
	NickName string     `json:"nick_name"` // 昵称
	UserName string     `json:"user_name"` // 用户名
	Password string     `json:"password"`  // 密码
	Role     ctype.Role `json:"role"`      // 权限
}

func (AdminUserApi) UserAdd(c *gin.Context) {
	var req UserAddReq
	if err := c.ShouldBindJSON(&req); err != nil {
		logrus.Error(err)
		panic(err)
	}
	// 查询是否存在
	var user models.UserModel
	err := global.DB.Where("user_name = ?", req.UserName).Take(&user).Error
	// 查询到了err就是nil 没查询到会有出错误
	if err == nil {
		panic("用户名已经存在")
	}
	ip, addr := utils.GetAddrByGin(c)
	// 添加用户
	err = global.DB.Create(&models.UserModel{
		NickName:   req.NickName,
		UserName:   req.UserName,
		Password:   utils.HashPwd(req.Password),
		Avatar:     "/uploads/default_avatar.jpg,",
		IP:         ip,
		Role:       req.Role,
		SignStatus: ctype.SignEmail,
		Addr:       addr,
	}).Error
	if err != nil {
		logrus.Error(err)
		panic(err)
	}
	res.OkWithMessage("添加用户成功", c)
}
